package com.g4.shoppingback.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Security配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置Security安全设置,米商后台管理系统采用Oauth2认证,
     * 所以这里不做设置或设置全部放行
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().
                csrf().disable()   //跨站请求伪造,开启后post请求无法通过
                .authorizeRequests()    //开始配置认证规则
                .anyRequest().permitAll();   //其他全部放行
                //.anyRequest().authenticated()
    }

    /**
     * 对密码加密
     * @return SHA-256+随机盐+密钥
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 为Oauth2提供认证对象
     * @return 返回认证管理器
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 开启Security跨域请求
     * @return 跨域配置对象
     */
    //@Bean 在跨域配置类重新配置了
    public CorsFilter corsFilter(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        //UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 失效
        //source.registerCorsConfiguration("/**",corsConfiguration); 失效
        return new CorsFilter(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest httpServletRequest) {
                return corsConfiguration;
            }
        });
    }
}
